<template>
  <div style="height: 80vh">
    <el-scrollbar style="height: 100%">
      <el-tree
        ref="tree"
        :data="data"
        :default-expanded-keys="defaultKey"
        node-key="id"
        @node-click="handleNodeClick"
        :expand-on-click-node="false"
      >
        <!-- default-expand-all -->
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span style="margin-right: 20px">{{ data.name }}</span>
          <span>
            <el-button
              class="el-icon-edit"
              type="text"
              size="mini"
              @click.stop="() => edit(node, data)"
            >
            </el-button>
            <el-button
              class="el-icon-delete"
              type="text"
              size="mini"
              @click.stop="() => remove(node, data)"
            >
            </el-button>
          </span>
        </span>
      </el-tree>
    </el-scrollbar>
    <el-dialog
      title="修改"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <span>
        <el-input v-model="name" placeholder="名称"></el-input>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editSumbit">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getTree, deleteData, editData } from "@/api/system/city.js";
import Bus from "../eventBus/bus.js";

export default {
  data() {
    return {
      data: [],
      nodeData: [],
      nodeMsg: "",
      node: "",
      defaultKey: ["36"],
      flag: false,
      dialogVisible: false,
      name: "",
    };
  },
  created() {
    this.getTreeData();
  },
  mounted() {
    this.update();
  },
  methods: {
    getTreeData() {
      getTree().then((res) => {
        if (res.data) {
          this.data = res.data;
          // 刷新数据后获取最新的节点信息
          if (this.flag) {
            this.getNodeMsg();
            this.flag = false;
          } else {
            // 避免新增或者删除之后执行两次发起data事件
            Bus.$emit("data", this.data[0].children);
          }
        } else {
         this.$modal.msgError("获取市区信息失败");
        }
      });
    },
    remove(node) {
      this.nodeMsg = node.data;
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteData(node.data.id).then((res) => {
          if (res.code == 200) {
           this.$modal.msgSuccess("删除成功");
            this.flag = true;
            this.keepState(node.parent.data.id);
            this.getTreeData();
          }
        });
      });
    },
    // 获取当前节点信息
    getNodeMsg() {
      let id = "";
      const addMsg = this.$refs.tree.getCurrentNode();
      if (addMsg) {
        id = addMsg.id;
      } else {
        if (this.nodeMsg) {
          id = this.nodeMsg.pid;
        } else {
          // 用户没有点击节点和删除操作时进行添加操作直接获取全国的节点信息
          id = 0;
        }
      }
      this.$nextTick(() => {
        // 根据不同的id获取不同的节点信息
        this.node = this.$refs.tree.getNode(id);
        this.handleNodeClick(this.node.data, this.node);
      });
    },
    edit(node) {
      this.dialogVisible = true;
      this.nodeMsg = node;
      this.name = this.nodeMsg.data.name;
    },
    editSumbit() {
      const data = {
        name: this.name,
        id: this.nodeMsg.data.id,
        pid: this.nodeMsg.data.pid,
      };
      editData(data).then((res) => {
        if (res.code == 200) {
          this.dialogVisible = false;
         this.$modal.msgSuccess("修改成功");
          this.flag = true;
          this.keepState(this.nodeMsg.parent.data.id);
          this.getTreeData();
        }
      });
    },
    // 点击节点
    handleNodeClick(data, node) {
      this.getChildren(data, node);
      this.nodeExpendClick(node);
    },
    // 获取children数组传入卡片中循环输入框
    getChildren(data, node) {
      let clickData = [];
      // 点击社区时当该社区不存在小区时弹出提示
      if (node.level === 5 && data.children.length == 0) {
       this.$modal.msgError("该页面无法添加小区");
      } else {
        // 点击小区直接传点击本身的值给卡片渲染
        if (node.level === 6) {
          clickData.push(data);
        } else {
          // 除上述情况，点击任意节点都应该传节点的children数组
          // 不存在chlidren数组时直接传data中的id
          if (data.children.length !== 0) {
            clickData = data.children;
          } else {
            clickData.push(data.id);
          }
        }
      }
      Bus.$emit("data", clickData, node);
    },
    // 获取name，传递给卡片渲染
    nodeExpendClick(node) {
      this.nodeData = [];
      this.getParentData(node);
      Bus.$emit("nodeData", this.nodeData);
    },
    // 递归点击节点中每个parent，获取name存入数组
    getParentData(val) {
      if (val.parent) {
        this.nodeData.unshift(val.data.name);
        this.getParentData(val.parent);
      }
    },
    // 新增成功之后更新数据
    update() {
      Bus.$on("update", () => {
        this.defaultKey = ["36"];
        this.flag = true;
        this.keepState();
        this.getTreeData();
      });
    },
    // 根据key值保持下拉状态
    keepState(val) {
      this.$nextTick(() => {
        let key = "";
        if (val) {
          key = val;
        } else {
          key = this.$refs.tree.getCurrentKey();
        }
        if (key) {
          this.defaultKey.push(key);
          this.$refs.tree.setCurrentKey(key);
        }
      });
    },
  },
};
</script>

<style scoped>
::v-deep .el-scrollbar__wrap {
  overflow-x: hidden;
}
</style>
